import 'package:flutter/material.dart' hide Row;
import 'package:path_provider/path_provider.dart';
import 'package:sql3_demo/article.dart';
import 'package:sqlite3/sqlite3.dart';
import 'dart:io';

void main() async {
  // print('Using sqlite3 ${sqlite3.version}');
  WidgetsFlutterBinding.ensureInitialized();
  // 初始化数据库
  await initSql();

  runApp(const MaterialApp(
    debugShowCheckedModeBanner: false,
    home: MainApp(),
  ));
}

// 初始化数据库
Future initSql() async {
  final appDocumentsDirectory = await getApplicationDocumentsDirectory();
  final filePath = '${appDocumentsDirectory.path}/sqlite_database.db';

  // 在此处创建新文件，例如：
  final file = File(filePath);
  await file.create();
  print(filePath);
  // // 打开数据库连接
  final db = sqlite3.open(filePath);

  // 在这里执行你的数据库操作
  // Create a table and insert some data
  db.execute('''
    CREATE TABLE IF NOT EXISTS artists (
      id INTEGER NOT NULL PRIMARY KEY,
      name TEXT NOT NULL
    );
  ''');
  db.dispose();
}

class MainApp extends StatefulWidget {
  const MainApp({super.key});
  @override
  State<MainApp> createState() => _MainAppState();
}

class _MainAppState extends State<MainApp> {
  List<Article> articles = [];
  late TextEditingController textEditingController;
  late FocusNode focusNode;
  int currentId = 0;

  final GlobalKey<ScaffoldMessengerState> scaffoldMessengerKey =
      GlobalKey<ScaffoldMessengerState>();

  @override
  void initState() {
    super.initState();
    textEditingController = TextEditingController(text: "");
    focusNode = FocusNode();
    getArticles();
  }

  /// 获取所有文章作者
  Future getArticles() async {
    final appDocumentsDirectory = await getApplicationDocumentsDirectory();
    final filePath = '${appDocumentsDirectory.path}/sqlite_database.db';
    final db = sqlite3.open(filePath);
    final ResultSet resultSet = db.select('SELECT * FROM artists');

    setState(() {
      articles = resultSet
          .map((row) => Article(name: row['name'], id: row['id']))
          .toList();
    });
  }

  /// 添加文章作者
  Future addArticle(String name) async {
    final appDocumentsDirectory = await getApplicationDocumentsDirectory();
    final filePath = '${appDocumentsDirectory.path}/sqlite_database.db';
    final db = sqlite3.open(filePath);
    final stmt = db.prepare('INSERT INTO artists (name) VALUES (?)');
    stmt
      ..execute([name])
      ..dispose();
    db.dispose();
  }

  /// 删除文章作者
  Future delArticle(int id) async {
    final appDocumentsDirectory = await getApplicationDocumentsDirectory();
    final filePath = '${appDocumentsDirectory.path}/sqlite_database.db';
    final db = sqlite3.open(filePath);
    final stmt = db.prepare('DELETE FROM artists where id = ?');
    stmt
      ..execute([id])
      ..dispose();
    db.dispose();
  }

  // 更新文章作者
  Future updateArticle(int id, String name) async {
    final appDocumentsDirectory = await getApplicationDocumentsDirectory();
    final filePath = '${appDocumentsDirectory.path}/sqlite_database.db';
    final db = sqlite3.open(filePath);
    final stmt = db.prepare('UPDATE artists set name = ? where id = ?');
    stmt
      ..execute([name, id])
      ..dispose();
    db.dispose();
  }

  @override
  void dispose() {
    // TODO: implement dispose
    textEditingController.dispose();
    focusNode.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return ScaffoldMessenger(
      key: scaffoldMessengerKey,
      child: Scaffold(
        body: SafeArea(
          child: GestureDetector(
            onTap: () {
              focusNode.unfocus();
            },
            child: Column(
              children: [
                Padding(
                  padding: const EdgeInsets.all(8.0),
                  child: TextField(
                    focusNode: focusNode,
                    controller: textEditingController,
                    decoration: const InputDecoration(
                      hintText: '请输入内容', // 设置提示文字
                    ),
                  ),
                ),
                Expanded(
                  child: ListView(
                    physics: const BouncingScrollPhysics(),
                    children: articles.map((Article item) {
                      return ListTile(
                        title: Text("name:${item.name}"),
                        subtitle: Text("id:${item.id}"),
                        onTap: () {
                          setState(() {
                            currentId = item.id;
                          });
                          textEditingController.text = item.name;
                        },
                        trailing: ElevatedButton(
                          child: const Text("删除"),
                          onPressed: () {
                            showDialog(
                              context: context,
                              builder: (BuildContext context) {
                                return AlertDialog(
                                  title: const Text('温馨提示'),
                                  content: const Text('是否确定删除该数据'),
                                  actions: <Widget>[
                                    TextButton(
                                      child: const Text('cancel'),
                                      onPressed: () {
                                        Navigator.of(context).pop();
                                      },
                                    ),
                                    TextButton(
                                      child: const Text(
                                        'OK',
                                        style: TextStyle(
                                          color: Colors.red,
                                        ),
                                      ),
                                      onPressed: () async {
                                        await delArticle(item.id);
                                        const snackBar = SnackBar(
                                          backgroundColor: Colors.blue,
                                          content: Text(
                                            '删除成功',
                                            style: TextStyle(
                                              color: Colors.white,
                                            ),
                                          ),
                                        );
                                        scaffoldMessengerKey.currentState!
                                            .showSnackBar(snackBar);
                                        getArticles();
                                        Navigator.of(context).pop();
                                      },
                                    )
                                  ],
                                );
                              },
                            );
                          },
                        ),
                      );
                    }).toList(),
                  ),
                ),
              ],
            ),
          ),
        ),
        floatingActionButton: FloatingActionButton(
          child: const Text("add"),
          onPressed: () async {
            if (textEditingController.text.isEmpty) {
              const snackBar = SnackBar(
                content: Text('姓名不能为空'),
              );
              scaffoldMessengerKey.currentState!.showSnackBar(snackBar);
              return;
            }
            if (currentId != 0) {
              // 更新文章
              await updateArticle(currentId, textEditingController.text);
              setState(() {
                currentId = 0;
              });
              const snackBar = SnackBar(
                content: Text('更新成功'),
              );
              scaffoldMessengerKey.currentState!.showSnackBar(snackBar);
              getArticles();
              return;
            }

            // 新增文章
            await addArticle(textEditingController.text);
            textEditingController.text = "";

            const snackBar = SnackBar(
              content: Text('新增成功'),
            );
            scaffoldMessengerKey.currentState!.showSnackBar(snackBar);
            getArticles();
          },
        ),
      ),
    );
  }
}
